const WEEK = ['日', '一', '二', '三', '四', '五', '六']
const NO_DATE = '---'
/**
 * 日期转字符串
 *
 * @param {any} date
 * @param {string} [formatStr='yyyyMMdd']
 * @returns
 */
export const date2Str = (date, formatStr = 'yyyyMMdd') => {
  if (!date) {
    return NO_DATE
  }
  if (!(date instanceof Date)) {
    date = new Date(date)
  }
  const fullYear = date.getFullYear()
  const year = date.getYear()
  const month = date.getMonth() + 1
  const day = date.getDay()
  const dt = date.getDate()
  const hours = date.getHours()
  const minutes = date.getMinutes()
  const seconds = date.getSeconds()
  formatStr = formatStr
    .replace(/yyyy|YYYY/, fullYear)
    .replace(/yy|YY/, year > 9 ? (year % 100).toString() : `0${year}`)
    .replace(/MM/, month > 9 ? month.toString() : `0${month}`)
    .replace(/M/g, month)
    .replace(/w|W/g, WEEK[day])
    .replace(/dd|DD/, dt > 9 ? dt.toString() : `0${dt}`)
    .replace(/d|D/g, dt)
    .replace(/hh|HH/, hours > 9 ? hours.toString() : `0${hours}`)
    .replace(/h|H/g, hours)
    .replace(/mm/, minutes > 9 ? minutes.toString() : `0${minutes}`)
    .replace(/m/g, minutes)
    .replace(/ss|SS/, seconds > 9 ? seconds.toString() : `0${seconds}`)
    .replace(/s|S/g, seconds)
  return formatStr
}

/**
 * 获取当前时间字符串
 *
 * @param {string} [formatStr='yyyy/MM/dd hh:mm:ss']
 * @returns
 */
export const getTimestamp = (formatStr = 'yyyy/MM/dd hh:mm:ss') => date2Str(new Date(), formatStr)

/**
 * 获取当前日期字符串
 *
 * @param {string} [formatStr='yyyyMMdd']
 * @returns
 */
export const getDate = (formatStr = 'yyyyMMdd') => date2Str(new Date(), formatStr)

// YYYYMMDD hh:mm:ss
export const getNowTime = () => {
  const dt = new Date()
  dt.setMinutes(dt.getMinutes() - dt.getTimezoneOffset())
  return dt
    .toISOString()
    .replace(/[-]/g, '')
    .replace(/T/g, ' ')
    .substr(0, 17)
}

export const parseNowTime = time => time.replace(/-/g, '')

export const betweenDays = (date1, date2) => {
  const sDate1 = Date.parse(date1)
  const sDate2 = Date.parse(date2)
  return Math.floor(Math.abs(sDate2 - sDate1) / (24 * 3600 * 1000))
}

export default {
  getDate,
  getTimestamp,
  date2Str,
  betweenDays
}
